<?php
use mytharcher\sdk\alipay\Alipay;

class PayAction extends Action{
	
 	function wechat(){
		$this->theme('Bizcard');
		Log::write(">>>>>>>>>>>>微信支付start<<<<<<<<");
		Vendor("WxPay.AutoLoad");
		$logHandler= new CLogFileHandler(LOG_PATH."/Pay-".date('Y-m').'.log');
		PayLog::Init($logHandler, 15);
		
		$order_no = $_GET['order_no'];
		$ob = M("csl_order");
		$info = $ob->where(array('order_no'=>$order_no))->find();
		
		if (PayAction::is_weixin()){
		    Log::write(">>>>>>>>>>>>>>Pay:wechat<<<<<<<<");
// 		if ($_GET['from'] == 'wechat'){
    		//①、获取用户openid
       	 	$tools = new JsApiPay();
    		$openId = $tools->GetOpenid();
    		
    		PayLog::DEBUG("\r\n\r\n******收到微信支付申请******\r\n\r\n");
    		PayLog::DEBUG("开始处理");
    		PayLog::DEBUG("本地路径：".$_SERVER['REQUEST_URI']);
    		//②、统一下单
    		$input = new WxPayUnifiedOrder();
    		$input->SetBody("商品收款");
    		$input->SetAttach("Att:".$order_no);
    		$input->SetOut_trade_no($info['order_no']);
    		$input->SetTotal_fee($info['order_price']*100);
//     		$input->SetTime_start(date("YmdHis"));
    // 		$input->SetTime_expire(date("YmdHis", time() + 200));
    		$input->SetGoods_tag("tag:".$order_no);
    		$input->SetNotify_url("http://www.25mp.cn/OrderCheck/Notify");
    		$input->SetOpenid($openId);
    		$input->SetSpbill_create_ip($_SERVER['REMOTE_ADDR']);
    		$input->SetTrade_type("JSAPI");
    		$order = WxPayApi::unifiedOrder($input);
    		if($order['return_code']=='FAIL'){
    			PayLog::DEBUG("微信支付参数组装失败：".print_r($input,true));
    		}else{
    			PayLog::DEBUG("微信支付参数组装成功：".print_r($input,true));
    		}
    		
    		$jsApiParameters = $tools->GetJsApiParameters($order); 
    		
    		$this->assign('info',$info);
    		$this->assign('jsApiParameters',$jsApiParameters);
    		$this->assign('order_no', $order_no);
    		$this->display('Pay:wechat');  
		}else {  //支付宝支付 
		    $alipay = new Alipay([
		        // 支付完成异步返回地址
		        'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].'/OrderCheck/AliNotify',
		        // 支付完成同步返回地址
		        'return_url' => 'http://'.$_SERVER['HTTP_HOST'].'/Pay/orderPaySuccess/orderno/'.$order_no.'/mobile/'.$info["shipping_mobile"],
		        
		        // 支付宝商家 ID
		        'partner'      => C("ALIPAY_PARTNER"),
		        // 支付宝商家 KEY
		        'key'          => C("ALIPAY_KEY"),
		        // 支付宝商家注册邮箱
		        'seller_email' => C("ALIPAY_EMAIL")
		    ], 'wap');
		    $params = $alipay->prepareMobileTradeData(array(
		        'out_trade_no'      => $order_no,
		        'subject'           => '名片',
		        'total_fee'         => $info['order_price'],
		        'body'              => '名片订单支付',
		        'show_url'          => 'http://'.$_SERVER['HTTP_HOST'].'/index/Home/init',
		        'anti_phishing_key' => '',
		        'exter_invoke_ip'   => '',
		        'it_b_pay'          => '2m',
		        '_input_charset'    => 'utf-8'
		    ));
		    $body = $alipay->buildRequestFormHTML($params, 'get');
		    // 输出 HTML 到浏览器，JS 会自动发起提交
		    echo $body;
		}
	} 

	function pay_mobile(){
	
	    $alipay = new Alipay([
	        // 支付完成异步返回地址
	        'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].'/OrderCheck/AliNotify',
	        // 支付完成同步返回地址
	        'return_url' => 'http://'.$_SERVER['HTTP_HOST'].'/',
	        // 支付宝商家 ID
	        'partner'      => C("ALIPAY_PARTNER"),
	        // 支付宝商家 KEY
	        'key'          => C("ALIPAY_KEY"),
	        // 支付宝商家注册邮箱
	        'seller_email' => C("ALIPAY_EMAIL")
	    ], 'wap');
	    $params = $alipay->prepareMobileTradeData(array(
	        'out_trade_no'      => '10000002',
	        'subject'           => '名片',
	        'total_fee'         => '0.01',
	        'body'              => '名片',
	        'show_url'          => 'http://'.$_SERVER['HTTP_HOST'].'/index/Home/init',
	        'anti_phishing_key' => '',
	        'exter_invoke_ip'   => '',
	        'it_b_pay'          => '2m',
	        '_input_charset'    => 'utf-8'
	    ));
	    $body = $alipay->buildRequestFormHTML($params, 'get');
	    // 输出 HTML 到浏览器，JS 会自动发起提交
	    echo $body;
	     
	}
	
	function pay_web(){
	    $alipay = new Alipay([
	        // 支付完成异步返回地址
	        'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].'/OrderCheck/AliNotify',
	        // 支付完成同步返回地址
	        'return_url' => 'http://'.$_SERVER['HTTP_HOST'].'/',
	        // 支付宝商家 ID
	        'partner'      => C("ALIPAY_PARTNER"),
	        // 支付宝商家 KEY
	        'key'          => C("ALIPAY_KEY"),
	        // 支付宝商家注册邮箱
	        'seller_email' => C("ALIPAY_EMAIL")
	    ]);
	    $body = $alipay->buildRequestFormHTML(array(
	        'out_trade_no'      => '10000002',
	        'subject'           => '名片',
	        'total_fee'         => '0.01',
	        'body'              => '名片',
	        'show_url'          => 'http://'.$_SERVER['HTTP_HOST'].'/index/Home/init',
	        'anti_phishing_key' => '',
	        'exter_invoke_ip'   => '',
	        'it_b_pay'          => '2m',
	        '_input_charset'    => 'utf-8'
	    ));
	    // 输出 HTML 到浏览器，JS 会自动发起提交
	    echo $body;
	}
	
	function wechatpreview(){
		
		$order_no = $_GET['orderno'];
		$ob = M("sp_orders");
		$info = $ob->where(array('order_no'=>$order_no))->find();
		
		$this->assign('info',$info);
		
		$this->display('Shop:order_payment');
	}
	
	//判断访问终端是否是微信浏览器
	function is_weixin() {
	    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
	        return true;
	    } return false;
	}
	
	//扫码支付
	function orderqrpay(){
		
		Vendor("WxPay.AutoLoad");
		
		$order_no = $_GET['orderno'];
		$ob = M("sp_orders");
		$info = $ob->where(array('order_no'=>$order_no))->find();
		
		// 扫码支付  Begin -------------------------------------------------------
		$notify = new NativePay();

		$input = new WxPayUnifiedOrder();
		$input->SetBody("商品收款");
		$input->SetAttach("Att:".$order_no);
		$input->SetOut_trade_no($order_no.rand(10,99));
		$input->SetTotal_fee($info['amount']*100);
		$input->SetTime_start(date("YmdHis"));
		$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag("tag:".$order_no);
		$input->SetNotify_url("http://console.o-tap.cn/Notify/Notify.php");
		$input->SetTrade_type("NATIVE");
		$input->SetProduct_id("Pid:".$order_no);
		$result = $notify->GetPayUrl($input);
		$url2 = $result["code_url"];
		
		$this->assign('info',$info);
		$this->assign('url',$url2);
// 		dayin($result);
		$this->display('Shop:orderpay');
	}
	
	function qrcode(){
		error_reporting(E_ERROR);
		Vendor("phpqrcode.phpqrcode");
		$url = urldecode($_GET["data"]);
		QRcode::png($url);
	}
	
	function orderPaySuccess(){
		$this->theme('Bizcard');
		$this->assign('orderno', $_GET['orderno']);
		$this->assign('mobile', $_GET['mobile']);
		Log::write("hash===".session("hash"));
		$this->assign('hash', session("hash"));
		$this->display('Pay:orderPaySuccess');
	}
	
	function orderPayFailure(){
		$this->theme('Bizcard');
		$this->assign('hash', session("hash"));
		$this->display('Pay:orderPayFailure');
	}
	
	/**
	 * 赠送码支付
	 */
	function payFreeCode(){
		$this->theme('Bizcard');
		if ($_POST){
			$ob = M("csl_paycode");
			//查询赠送码
			$info = $ob->where(array("code"=>$_POST["freeCode"],"status"=>"1"))->find();
			$db = M("csl_order");
			//查找未支付订单
			$oinfo = $db->where(array("order_no"=>$_POST["order_no"],'order_status'=>array('lt','3')))->find();
			
			if ($info){
				
				//如果是首单
			    $oc = M("csl_customer");
			    $cinfo = $oc->where(array('cid'=>$oinfo['cid']))->find();
// 				$fisrtOrder = $db->where(array('order_status'=>array('egt','7'),'cid'=>$oinfo['cid']))->find();
// 				if(empty($fisrtOrder) && !empty($info['uid'])){
				if(empty($cinfo['uid']) && !empty($info['uid'])){
					//首单
// 					$oc = M("csl_customer");
					//设置该用户的uid 为 赠送券的UID
					$oc->where(array('cid'=>$oinfo['cid']))->setField('uid', $info['uid']);
					CommonFunc::Log("订单[{$oinfo['order_no']}]使用制作码支付,设置改顾客代理商为制作码代理商[{$info['uid']}]",'customer');
					
					$db->where(array("order_no"=>$_POST["order_no"]))->setField('uid', $info['uid']);
				}else{
// 				    $db->where(array("order_no"=>$_POST["order_no"]))->setField('uid', $info['uid']);
				}
				
				
				
				//check = 1 不参与业绩分配
				$data = array("order_no"=>$_POST["order_no"],"order_status"=>"7","check"=>'1');
				//更新订单状态
				$result = $db->where(array("order_no"=>$_POST["order_no"]))->save($data);
				if ($result){
					$map = array("order_no"=>$_POST["order_no"],
								 "utime"=>date("Y-m-d H:i:s", time()),
								 "status"=>"0");
					//回写赠送码状态
					$ob->where(array("code_id"=>$info["code_id"]))->save($map);
					
					//记录支付日志
					$log = M("log_transaction");
					$content2["order_no"] = $_POST["order_no"];
					$content2["uid"] = $info["uid"];
					$content2["action"] = "制作码支付";
					$content2["msg"] = "制作码[".$_POST["freeCode"]."]支付金额:".$_POST["order_price"];
					$content2["session"] = session_id();
					$content2["ctime"] =  date("Y-m-d H:i:s", time());
					$log->add($content2);
					
					$this->assign("orderno", $_POST["order_no"]);
					$this->display("/Pay/orderPaySuccess");
					
					//订单分成
					file_get_contents('http://www.25mp.cn/OrderCheck/OrderCheck/order_no/'.$_POST["order_no"]);
					
					return;
				}
			}else{
				$this->error("制作码已使用或者输入有误");
				CommonFunc::Log("订单[{$oinfo['order_no']}]使用制作码支付,制作码已使用或者输入有误",'order');
				$this->display("/Pay/orderPayFailure");
				return;
			}
		}
	}
	
}



